package top.shiyiri.community.controller.advice;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import top.shiyiri.community.util.CommunityUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 统一异常处理
 * @author Aunean
 * @date 2022/3/16 14:38
 */
@ControllerAdvice(annotations = Controller.class)
public class ExceptionAdvice {

    private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);

    @ExceptionHandler(Exception.class)
    public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        logger.error("服务器发生异常：" + e.getMessage());
        for (StackTraceElement element: e.getStackTrace()) {
            logger.error(element.toString());
        }

        String header = request.getHeader("x-requested-with");
        System.out.println("ExceptionAdvice：header：" + header);
        if ("XMLHttpRequest".equals(header)) {
            response.setContentType("application/plain;charset=utf-8");
            response.getWriter().write(CommunityUtil.getJSONString(1,"服务器异常"));
        } else {
            response.sendRedirect(request.getContextPath() + "/error");
        }
    }
}
